import Taro, {Component} from "@tarojs/taro";
import {View, Image, Text, Picker} from "@tarojs/components";
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime} from '../../utils/common'
import * as api from "../../api/api";

import './mall.less'
import right_white from "../../assets/img/right_white.png";
import right from "../../assets/img/right.png";
import address from "../../assets/img/icon_58.png";

// 确认订单
interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class Personnel extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    defaultAddress: null, // 用户选择的地址或是默认地址
    itemId: null, // 商品ID
    item: {},
    integralArr: ['不使用积分'],
    integralIndex: 0,
    pointMoney: 0, // 积分兑换的钱
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'确认订单' })
    let itemId = this.$router.params.id
    let userCart = getRuntime().getStorage('userCart')
    let userInfo = getRuntime().getUserInfo()
    let userPoint = userInfo.points
    let integralArr = ['不使用积分']
    if(itemId && userCart){
     // console.log(itemId)
     // console.log(userCart)
      this.setState({item: userCart})
      let pointMoney = (userPoint*(userCart.pointValue/100)).toFixed(2)
      if(userPoint>0 && userCart.pointValue>0){ // 用户有积分且商品金额需要大于积分所能抵扣的钱
        integralArr.unshift(`${userPoint}积分(-${pointMoney}元)`)
        this.setState({
          integralArr,pointMoney
        })
      }else {
        this.setState({
          integralArr: ['暂无可用积分']
        })
      }
    }
    this.getUserAddress()
  }

  // 选择地址后更新用户收货地址
  componentDidShow(): void {
    this.getUserAddress()
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  // 获取用户收货地址
  getUserAddress(){
    // 获取用户选择的地址, 然后获取用户默认地址
    let defaultAddress: any = getRuntime().getStorage('userSelectAddress') || null
    // 如果用户没有选择地址，从缓存中获取用户设置的默认地址
    if(defaultAddress){
      this.setState({
        defaultAddress
      })
    } else {
      // 没有缓存从服务器获取地址
      let { PointMallStore } = this.props.stores
      PointMallStore.getUserDefaultAddress({
        callback: res => {
           defaultAddress = res || null
           this.setState({
             defaultAddress
           })
        }
      })
    }
  }

  changePicker(e) {
    this.setState({
      integralIndex: e.detail.value
    })
  }

  // 立即付款, 先下单再付款
  placeOrder() {
    let {item, defaultAddress,integralArr,integralIndex} = this.state
    if(!defaultAddress){getRuntime().showToast('请添加收货地址~'); return}
    let { PointMallStore } = this.props.stores
    let itemSpecId = item.specNoId
    let qty = item.itemNum
    let message = ''
    let addressId = defaultAddress.id
    PointMallStore.placeOrder({
      form: {
        itemSpecId,
        qty,
        message,
        addressId,
        orderType: 1
      },
      callback: (res) => {
        // 下单成功
        this.pay(res)
      }
    })
  }

  // 支付
  pay(orderInfo: api.YNJWTPointMallVOOrderVO) {
    let { integralArr,integralIndex, pointMoney, item } = this.state
    let isPayPoints = !!(integralArr.length>1 && integralIndex === 0)
   /*getRuntime().commonPay(orderInfo.id,5,isPayPoints, () => {
      getRuntime().navigateTo('/pages/mall/pay_success?id='+orderInfo.id)
    })*/
   let { PointMallStore } = this.props.stores
    if(pointMoney >= item.itemPrice && isPayPoints && item.freight === 0) {
      PointMallStore.buyItemWithPoints({
        form: { orderId: orderInfo.id },
        callback: () => {
          getRuntime().navigateTo('/pages/mall/pay_success?id='+orderInfo.id)
        }
      })
    }else {
      PointMallStore.pay({
        form: {
          orderId: orderInfo.id,
          payType: 1,
          isPayPoints,
        },
        callback: res => {
          // 支付
          // let payParams = JSON.parse(res.payParams)
          getRuntime().wxPay(res, () => {
            getRuntime().navigateTo('/pages/mall/pay_success?id='+orderInfo.id)
          })
        }
      })
    }
  }

  render() {
    let { defaultAddress,item,integralArr,integralIndex,pointMoney } = this.state
    // console.log(item)
    let itemNum = item.itemNum // 商品数量
    let itemFreight = item.freight*itemNum // 商品运费
    let itemPrice = item.itemPrice // 商品价格
    let itemPayPrice = itemPrice // 商品实际支付价格
    if(integralIndex === 0 ){
      // 使用积分
      if(itemPrice>pointMoney) { itemPayPrice = itemPrice-pointMoney }
      else { itemPayPrice = 0 }
    }
    let totalMoney = itemPayPrice + itemFreight // 总价
    let publicDonations = (itemPrice*(item.publicDonations/100)).toFixed(2) // 公益捐款
    return (
      <View className='mall-order-confirm'>
        {defaultAddress &&
        <View className='order-address' onClick={this.handelRouter.bind(this, '/pages/mall/address')}>
           <View className='has-address'>
              <Image className='address-icon' src={address} />
              <View className='info'>
                 <View className='name'>{defaultAddress.receiver}  {defaultAddress.receiverPhone}</View>
                 <View className='address'>{defaultAddress.receiverAddress}</View>
              </View>
              <Image className='drop-down-icon' src={right_white} />
           </View>
        </View>
        }
        {!defaultAddress &&
        <View className='order-address' onClick={this.handelRouter.bind(this, '/pages/mall/address')}>
           <View className='none-address'>新增收货地址
              <Image className='drop-down-icon' src={right_white} />
           </View>
        </View>
        }
        <View className='order-spec'>
          <View className='l'>
           <Image className='img' src={item.picture} />
            <View className='info'>
              <View className='list-title'>{item.name}</View>
              <View className='list-info'>
                {/*<Text>5kg</Text>
                <Text className='line'>|</Text>
                <Text>盒装</Text>*/}
                {item.itemSpec}
              </View>
            </View>
          </View>
          <View className={'r'}>
            <View className='list-price'>
              <Text className='list-small'>￥</Text>{item.itemSignPrice}</View>
            <View className='list-info' style={{textAlign: 'right'}}>
              <Text>x{item.itemNum}</Text>
            </View>
          </View>
        </View>

        <View className='select-spec'>
          <View className='title'>积分</View>
          <View className='drop-down-con'>
            <Picker className='input-picker' name='integral' mode='selector' range={integralArr} onChange={this.changePicker.bind(this,)}>
              <View className='tt'>
                <Text className='con'> {integralArr[integralIndex]} </Text>
                <Image className='drop-down-icon' src={right} />
              </View>
            </Picker>
          </View>
        </View>

        <View className='select-spec'>
          <View className='title color'>小计</View>
          <View className='drop-down-con'>
           {/* {integralIndex===0&&<Text className='con color'><Text className='list-small'>￥</Text>{itemPrice-pointMoney}</Text>}
            {integralIndex===1&&<Text className='con color'><Text className='list-small'>￥</Text>{itemPrice}</Text>}*/}
            <Text className='con color'><Text className='list-small'>￥</Text>{itemPayPrice}</Text>
          </View>
        </View>

        <View className='interval' />

        <View className='select-spec'>
          <View className='title'>运费</View>
          <View className='drop-down-con'>
            {itemFreight>0&& <Text className='con'><Text className='list-small'>￥</Text>{itemFreight}</Text>}
            {itemFreight<=0&& <Text className='con'>免费配送</Text>}
          </View>
        </View>

        {!defaultAddress&& <View className='none-address-tip'>
           *请在上方添加收货地址
        </View>}

        <View className='footer-block' />
        <View className='page-footer2 page-footer3'>
          <View className='all-price'>
            <View className='line'>
              已选 <Text className='color all-count'>{itemNum}</Text> 件商品，合计：
             {/* {integralIndex===0&& <Text className='color'><Text className='list-small'>￥</Text>{totalMoney-pointMoney}</Text>}
              {integralIndex===1&& <Text className='color'><Text className='list-small'>￥</Text>{totalMoney}</Text>}*/}
             <Text className='color'><Text className='list-small'>￥</Text>{totalMoney}</Text>
            </View>
            <View className='line gy'>
              公益捐款￥{publicDonations}元
            </View>
          </View>
          <View className='btn-submit' onClick={this.placeOrder.bind(this)}>立即付款</View>
        </View>
      </View>
    )
  }
}

export default Personnel
